package cn.cuilan.utils;

import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 文件上传工具类
 *
 * @author zhang.yan
 */
public class FileUpload {

    private static final Logger logger = LoggerFactory.getLogger(FileUpload.class);

    /**
     * 保存本地文件
     *
     * @param file     文件二进制数组
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @return 返回文件的绝对路径
     * @throws IOException IO异常
     */
    public static String saveLocalFile(byte[] file, String filePath, String fileName) throws IOException {
        // 创建文件路径对象
        File dir = new File(filePath);
        if (!dir.exists()) {
            // 目录是否创建成功
            Assert.isTrue(dir.mkdirs());
        }
        String absolutePath = filePath + formatFileName(fileName);
        FileOutputStream fos = new FileOutputStream(absolutePath);
        fos.write(file);
        fos.flush();
        fos.close();
        logger.info("file saved path: " + absolutePath);
        return absolutePath;
    }

    /**
     * 格式化文件名称，yyyy-MM-dd-hh-mm-ss-nnnnnnnnn.type
     *
     * @param fileName 原始文件名
     * @return 返回日期格式的文件名
     */
    public static String formatFileName(String fileName) {
        LocalDateTime now = LocalDateTime.now();
        String formatName = now.getYear() + "-"
                + now.getMonthValue() + "-"
                + now.getDayOfMonth() + "-"
                + now.getHour() + "-"
                + now.getMinute() + "-"
                + now.getSecond() + "-"
                + now.getNano();
        return formatName + fileName.substring(fileName.lastIndexOf("."), fileName.length());
    }

}
